import 'package:carousel_slider/carousel_slider.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart';
import 'package:jd_flutter/base/foundation/flutter_extension.dart';
import 'package:jd_flutter/base/foundation/jd_colors.dart';
import 'package:jd_flutter/base/foundation/jd_device.dart';
import 'package:jd_flutter/base/net/jd_request.dart';
import 'package:jd_flutter/base/utils/jd_log.dart';
import 'package:jd_flutter/base/widget/basic/base_lifecycle_page.dart';
import 'package:jd_flutter/base/widget/basic/jd_app_bar.dart';
import 'package:jd_flutter/base/widget/image/jd_network_image.dart';
import 'package:jd_flutter/base/widget/ui/jd_button.dart';
import 'package:jd_flutter/modules/config/url_constant.dart';
import 'package:jd_flutter/modules/pages/home/models/home_model.dart';
import 'package:jd_flutter/modules/pages/home/widgets/home_left_scroll_widget.dart';
import 'package:jd_flutter/modules/pages/home/widgets/home_list_bottom_widget.dart';
import 'package:jd_flutter/modules/router/router_contract_page.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends BaseLifecycleState<HomePage>
    with TickerProviderStateMixin {
  TabController? tabController;
  List<String> tabs = [
    "精彩",
    "综合推荐",
  ];

  Future<HomeModel>? futureBuilderFuture;

  @override
  void initState() {
    setRequestFuture();
    tabController =
        TabController(vsync: this, length: tabs.length, initialIndex: 0);
    super.initState();
  }

  setRequestFuture() {
    futureBuilderFuture = _gerData();
  }

  Future<HomeModel> _gerData() async {
    Map response = await JDApiRequest.get(JDNetworkUrl.home).request;
    HomeModel homeModel =
        HomeModel.fromJson(response.getMapNotNull(kResponseData));
    return homeModel;
  }

  @override
  void dispose() {
    super.dispose();
  }

  double headViewH = 200;

  int currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: JDColors.backgroundColor,
        appBar: JDAppBar(
          title: '首页',
          showBackButton: false,
          actionWidgets: [
            JDButton(
              minHeight: 30,
              minWidth: 40,
              radius: 10,
              backgroundColor: Colors.white,
              onPressed: () {
                RouterContractPage.instance.detailPage
                    .push(context, params: {'id': '123'});
              },
              text: '点击',
            )
          ],
        ),
        body: FutureBuilder<HomeModel>(
            future: futureBuilderFuture,
            builder: (BuildContext context, AsyncSnapshot<HomeModel> snapshot) {
              if (snapshot.data == null) {
                return Container(
                  color: Colors.white,
                  width: MediaQuery.of(context).size.width,
                  height: MediaQuery.of(context).size.height,
                );
              }

              HomeModel homeModel = snapshot.data!;

              return ExtendedNestedScrollView(
                onlyOneScrollInBody: true,
                headerSliverBuilder:
                    (BuildContext context, bool innerBoxIsScrolled) {
                  return <Widget>[
                    SliverAppBar(
                      leading: Gap.empty,
                      shadowColor: Colors.transparent,
                      surfaceTintColor: JDColors.backgroundColor,
                      foregroundColor: JDColors.backgroundColor,
                      pinned: true,
                      floating: true,
                      expandedHeight: headViewH + 50,
                      backgroundColor: JDColors.backgroundColor,
                      flexibleSpace: FlexibleSpaceBar(
                          collapseMode: CollapseMode.pin,
                          background: SizedBox(
                              width: JDDevice.width,
                              height: headViewH + 50,
                              child: Stack(
                                children: [
                                  Container(
                                      width: JDDevice.width,
                                      height: headViewH,
                                      clipBehavior: Clip.hardEdge,
                                      decoration: const BoxDecoration(
                                        color: Colors.white,
                                      ),
                                      child: Stack(
                                        alignment:
                                            AlignmentDirectional.bottomCenter,
                                        children: [
                                          CarouselSlider(
                                            options: CarouselOptions(
                                                height: headViewH,
                                                viewportFraction: 1,
                                                onPageChanged: (index, reason) {
                                                  setState(() {
                                                    currentIndex = index;
                                                  });
                                                  jdLog(
                                                      'currentIndex ----$index');
                                                }),
                                            items: homeModel.imageList
                                                ?.mapIndex((index, url) {
                                              return Builder(
                                                builder:
                                                    (BuildContext context) {
                                                  return Container(
                                                      width: JDDevice.width,
                                                      margin: const EdgeInsets
                                                          .symmetric(
                                                          horizontal: 5.0),
                                                      child: JDNetworkImage(
                                                        url: url,
                                                        fit: BoxFit.cover,
                                                      ));
                                                },
                                              );
                                            }).toList(),
                                          ),
                                          Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.end,
                                              children: [
                                                ...(homeModel.imageList ?? [])
                                                    .mapIndex((index, item) {
                                                  return GestureDetector(
                                                    onTap: () =>
                                                        {}, // 这里可以添加点击事件
                                                    child: Container(
                                                      width: 8.0,
                                                      height: 8.0,
                                                      margin: const EdgeInsets
                                                          .symmetric(
                                                          vertical: 8.0,
                                                          horizontal: 4.0),
                                                      decoration: BoxDecoration(
                                                        shape: BoxShape.circle,
                                                        color: currentIndex ==
                                                                index
                                                            ? Colors.blue
                                                            : Colors.grey,
                                                      ),
                                                    ),
                                                  );
                                                }).toList(),
                                                10.hGap
                                              ]),
                                        ],
                                      )),
                                ],
                              ))),
                      bottom: TabBar(
                          controller: tabController,
                          // 取消水波纹效果
                          splashFactory: NoSplash.splashFactory,
                          padding: const EdgeInsets.only(left: 0),
                          isScrollable: true,
                          indicatorSize: TabBarIndicatorSize.label,
                          dividerHeight: 0,
                          indicatorWeight: 4,
                          indicatorPadding:
                              const EdgeInsets.fromLTRB(5, 0, 5, 0),
                          indicator: UnderlineTabIndicator(
                              borderRadius: BorderRadius.circular(2),
                              borderSide: const BorderSide(
                                  width: 4.0, color: Colors.blue),
                              insets: const EdgeInsets.only(bottom: 12)),
                          indicatorColor: Colors.blue,
                          // 选中字体颜色
                          labelStyle: const TextStyle(
                              color: Color(0xFF222222),
                              fontSize: 16,
                              fontWeight: FontWeight.w600),
                          // 没选中字体颜色
                          unselectedLabelStyle: const TextStyle(
                              color: Color(0xFF999999), fontSize: 15),
                          tabAlignment: TabAlignment.center,
                          tabs: tabs.mapIndex((index, tabName) {
                            return Tab(
                              height: 50,
                              child: Text(
                                ' $tabName ',
                              ),
                            );
                          }).toList()),
                    )
                  ];
                },
                body: TabBarView(
                    controller: tabController,
                    children: tabs.mapIndex((index, element) {
                      if (index == 0) {
                        return HomeLeftScrollWidget(
                          homeModel: homeModel,
                        );
                      } else {
                        return GridView.builder(
                            /*
                            // 不能滚动
                             physics: const NeverScrollableScrollPhysics(),
                            //可以滑动 有弹性
                            BouncingScrollPhysics
                            //可以滑动 没有弹性
                            ClampingScrollPhysics
                           */
                            physics: const BouncingScrollPhysics(),
                            shrinkWrap: true,
                            padding: const EdgeInsets.fromLTRB(10, 10, 10, 10),
                            scrollDirection: Axis.vertical,
                            itemCount: 20,
                            gridDelegate:
                                const SliverGridDelegateWithFixedCrossAxisCount(
                                    childAspectRatio: 174.0 / 295.0,
                                    crossAxisCount: 2,
                                    mainAxisSpacing: 8,
                                    crossAxisSpacing: 7),
                            itemBuilder: (BuildContext context, int index) {
                              return GestureDetector(
                                onTap: () {
                                  jdLog('点击');
                                },
                                child: Container(
                                  clipBehavior: Clip.hardEdge,
                                  decoration: const BoxDecoration(
                                    color: Colors.white,
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(10)),
                                  ),
                                  child: Column(
                                    children: [
                                      Expanded(
                                          child: JDNetworkImage(
                                        url: getRandomImageUrl(),
                                      )),
                                      Container(
                                        height: 71,
                                        width: double.infinity,
                                        padding: const EdgeInsets.fromLTRB(
                                            8, 10, 8, 10),
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            const Text(
                                              '今天是个好日子',
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                  color: Color(0xFF222222),
                                                  fontSize: 14,
                                                  fontWeight: FontWeight.w600),
                                            ),
                                            10.vGap,
                                            const HomeBottomWidget(
                                              urlList: [
                                                testUrl,
                                                'https://upload-images.jianshu.io/upload_images/25564814-13bbc0f01ba5e9ea.jpg',
                                                'https://upload-images.jianshu.io/upload_images/25564814-45d904e388cf040a.jpg'
                                              ],
                                              count: '666',
                                            )
                                          ],
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              );
                            });
                      }
                    }).toList()),
              );
            }));
  }
}
